#include "SteerCamera.h"

SteerCamera::SteerCamera() : Camera(0, 0)
{
	lastMousePos = NULL;

	position.Set(0, 0, 0);
	lookTarget.Set(0, 0, -1.0f);

	yaw = 0.0f;
	pitch = 0.0f;
	roll = 0.0f;
	
	screenCentre.x = GetSystemMetrics(SM_CXSCREEN) / 2;
	screenCentre.y = GetSystemMetrics(SM_CYSCREEN) / 2;
	SetCursorPos(screenCentre.x, screenCentre.y);
}

void SteerCamera::Process(float ms)
{
	POINT cur_pos;
	GetCursorPos(&cur_pos);
	SetCursorPos(screenCentre.x, screenCentre.y);

	float sensitivity = 1.0f / 10.0f;

	if (cur_pos.x != screenCentre.x)
		yaw += (float)(cur_pos.x - screenCentre.x) * sensitivity;

	if (cur_pos.y != screenCentre.y)
		pitch += (float)(cur_pos.y - screenCentre.y) * sensitivity;

	//lookTarget.RotateY(rad(yaw));
	//lookTarget.RotateX(rad(pitch));

	//(*lastMousePos) = cur_pos;

	bool keys[256];

	keys['W'] = false;
	keys['A'] = false;
	keys['S'] = false;
	keys['D'] = false;
	keys['Q'] = false;
	keys['E'] = false;

	if (GetAsyncKeyState('W') & 0x8000) keys['W'] = true;
	if (GetAsyncKeyState('A') & 0x8000) keys['A'] = true;
	if (GetAsyncKeyState('S') & 0x8000) keys['S'] = true;
	if (GetAsyncKeyState('D') & 0x8000) keys['D'] = true;
	if (GetAsyncKeyState('Q') & 0x8000) keys['Q'] = true;
	if (GetAsyncKeyState('E') & 0x8000) keys['E'] = true;

	float ratio = ms / 5.0f;

	Vec3 moveVec(0, 0, -1);
	moveVec.RotateX(-rad(pitch));
	moveVec.RotateY(rad(yaw));
	
	if (keys['W'] == TRUE)
	{
		moveVec = moveVec * ratio;
		position = position + moveVec;
	}

	if (keys['S'] == TRUE)
	{
		moveVec = moveVec * ratio;
		position = position - moveVec;
	}

	if (keys['A'] == TRUE)
	{
		moveVec.y = 0;
		moveVec.Normalize();
		moveVec.RotateY(rad(90.0f));
		moveVec = moveVec * ratio;
		position = position - moveVec;
	}

	if (keys['D'] == TRUE)
	{
		moveVec.y = 0;
		moveVec.Normalize();
		moveVec.RotateY(rad(90.0f));
		moveVec = moveVec * ratio;
		position = position + moveVec;
	}

	if (keys['Q'] == TRUE)
	{
		position.y += ratio;
	}

	if (keys['E'] == TRUE)
	{
		position.y -= ratio;
	}
}

void SteerCamera::SetViewMatrix()
{
	glRotatef(roll, 0.0f, 0.0f, 1.0f);
	glRotatef(pitch, 1.0f, 0.0f, 0.0f);
	glRotatef(yaw, 0.0f, 1.0f, 0.0f);

	glTranslatef(-position.x, -position.y, -position.z);
}

Vec3 SteerCamera::GetPosition()
{
	return position;
}

Vec3 SteerCamera::GetTargetPosition()
{
	return lookTarget;
}

float SteerCamera::GetRoll()
{
	return roll;
}

void SteerCamera::SetPosition(Vec3 position)
{
	this ->position = position;
}

void SteerCamera::SetLookTarget(Vec3 lookTarget)
{
	this ->lookTarget = lookTarget;
}

void SteerCamera::SetRoll(float roll)
{
	this ->roll = roll;
}

float SteerCamera::GetTargetDistance()
{
	/*Vec3 camTarget = position + lookTarget;
	Vec3 v = camTarget - position;
	return v.GetLength();*/

	return 1.0f;
}